package com.hcc.flow.server.dao.sys;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.mapping.StatementType;

import com.hcc.flow.server.common.constant.Constant;
import com.hcc.flow.server.model.sys.Dep;
import com.hcc.flow.server.vo.sys.DepShordVO;
import com.hcc.flow.server.vo.sys.DepVO;
import com.hcc.flow.server.where.sys.DepWhere;

/**
 * DepDao
 * 
 * @author 韩长志 2019-11-19
 *
 */
@Mapper
public interface DepDao {

	@Select("select t.*,s.USER_NAME create_user_name from dep t LEFT JOIN sys_user s on t.create_user_id=s.USER_ID where t.dep_status='"
			+ Constant.DATA_STATUS_DELETE + "' order by t.sort_no,t.create_time")
	List<Dep> listAll();

	@Select("select t.*,s.USER_NAME create_user_name from dep t LEFT JOIN sys_user s on t.create_user_id=s.USER_ID where t.org_id=#{orgId} and t.dep_status!='"
			+ Constant.DATA_STATUS_DELETE + "' order by t.sort_no,t.create_time")
	List<DepVO> listByOrgId(String orgId);
	
	@Select("select count(t.dep_id) from dep t where t.org_id=#{orgId} and t.dep_status!='"+ Constant.DATA_STATUS_DELETE + "'")
	int countByOrgId(String orgId);

	@Select("select t.* from dep t where t.org_id=#{orgId} and t.dep_status='" + Constant.DATA_STATUS_TYPE_NORMAL
			+ "' order by t.sort_no,t.create_time")
	List<DepShordVO> listShordByOrgId(String orgId);

	@Select("select * from dep t where t.dep_id = #{id}")
	Dep getById(String id);

	@Select("select * from dep t where t.dep_code = #{depCode} and t.dep_status!='"+ Constant.DATA_STATUS_DELETE + "'")
	Dep getByDepCode(String depCode);

	@Delete("delete from dep where dep_id = #{id} or parent_id = #{id}")
	int delete(String id);

	int update(Dep dep);

	// @Options(useGeneratedKeys = true, keyProperty = "id")
	@SelectKey(statement = "select replace(UUID(),'-','')", keyProperty = "depId", before = true, statementType = StatementType.STATEMENT, resultType = String.class)
	@Insert("insert into dep(dep_id, org_id, dep_code, dep_name, dep_desc, parent_id, sort_no, dep_status, create_time, create_user_id, level) "
			+ "values(#{depId}, #{orgId}, #{depCode}, #{depName}, #{depDesc}, #{parentId}, #{sortNo}, '"
			+ Constant.DATA_STATUS_TYPE_NORMAL + "', now(), #{createUserId}, #{level})")
	int save(Dep dep);

	List<Dep> DepList(DepWhere params);

	@Update("<script>" + "update dep set dep_status=#{status} where dep_id in "
			+ "<foreach item='item' index='index' collection='ids' open='(' separator=',' close=')'>" + "#{item}"
			+ "</foreach>" + "</script>")
	int updateStatus(@Param("ids") List<String> ids, @Param("status") String status);
}
